<template>
    <view class="flex-1 flex flex-column overflow-auto">
        <template v-if="$utils.$system.isWechat() && WEBCONFIG.wx_state && nav === 'wechat'">
            <view class="flex-1 flex flex-column flex-x-center px-10">
                <view class="flex flex-center flex-column" v-if="showLogo">
                    <image :src="WEBCONFIG.web_logo" v-if="WEBCONFIG.web_logo" class="logo"></image>
                    <image src="@/static/logo.png" v-else class="logo"></image>
                </view>
                <view class="py-10">
                    <view class="flex flex-center">
                        <view class="bg-primary text-white rounded-round w-50 py-4 font-weight-600 text-center"
                            hover-class="bg-primary-dark-1" @tap="wxLogin">微信公众号一键登录</view>
                    </view>
                    <view class="flex flex-center mt-4">
                        <view class="h10 text-primary py-4" @tap.stop="nav = 'mobile'">手机号登录</view>
                    </view>
                    <view class="flex flex-center mt-4" @tap="form.agreement = !form.agreement">
                        <uni-icons type="circle-filled" v-if="form.agreement" color="var(--theme-color)" />
                        <uni-icons type="circle" v-else color="var(--theme-color)" />
                        <view class="h10 text-dark-light-5 pl-2">请阅读并同意</view>
                        <view class="h10 text-primary ml-2" @tap.stop="openAgreement">《用户协议》</view>
                    </view>
                </view>
            </view>
        </template>
        <template v-else>
            <!-- #ifdef H5 -->
            <view class="flex-1 flex flex-column flex-x-center px-10">
                <view class="bg-grey rounded-round flex flex-center px-4">
                    <view class="w-30px">
                        <uni-icons type="phone" size="30" color="var(--theme-color)"></uni-icons>
                    </view>
                    <input ref="mobileRef" v-model="mobile" type="tel"
                        class="flex-1 h4 font-weight-600 mx-4 py-4 text-primary" placeholder="手机号" placeholder-class="h8"
                        maxlength="13" @input="formatMobile">
                    <view class="w-30px">
                        <uni-icons v-if="mobile" type="close" size="30" color="var(--theme-color)"
                            @tap="mobile = ''"></uni-icons>
                    </view>
                </view>
                <view class="bg-grey rounded-round flex flex-center px-4 mt-6" v-if="WEBCONFIG.imgcode">
                    <view class="w-30px">
                        <uni-icons type="image" size="30" color="var(--theme-color)"></uni-icons>
                    </view>
                    <input v-model="form.imgcode" type="text" class="flex-1 h4 font-weight-600 mx-4 py-4 text-primary"
                        placeholder="图形验证码" placeholder-class="h8" maxlength="6">
                    <image :src="captchaUrl" class="captcha-image" mode="aspectFit" @tap="getCaptchaUrl" />
                </view>
                <view class="bg-grey rounded-round flex flex-center px-4 mt-6">
                    <view class="w-30px">
                        <uni-icons type="email" size="30" color="var(--theme-color)"></uni-icons>
                    </view>
                    <input v-model="form.vcode" type="tel" class="flex-1 h4 font-weight-600 mx-4 py-4 text-primary"
                        placeholder="验证码" placeholder-class="h8" maxlength="6">
                    <view class="h10 font-weight-600" @tap="getVcode"
                        :class="vcodeBtn.disabled ? 'text-dark-light-5' : 'text-primary'">{{ vcodeBtn.text }}</view>
                </view>
            </view>
            <!-- #endif -->
            <!-- #ifdef MP-WEIXIN -->
            <view class="flex-1 flex flex-column flex-x-center px-10">
                <view class="flex flex-center px-4 mb-10 flex-column">
                    <button open-type="chooseAvatar" @chooseavatar="chooseavatar" class="avatar-btn bg-grey">
                        <image v-if="form.avatar" :src="form.avatar" class="avatar" />
                        <uni-icons type="person-filled" size="30" color="var(--theme-color)" v-else />
                    </button>
                    <view class="h8 text-placeholder pt-2 font-weight-600">头像</view>
                </view>
                <view class="bg-grey rounded-round flex flex-center px-4">
                    <view class="w-30px">
                        <uni-icons type="person" size="30" color="var(--theme-color)"></uni-icons>
                    </view>
                    <input type="nickname" v-model="form.nickname" class="flex-1 h4 font-weight-600 mx-4 py-4 text-primary"
                        placeholder="昵称" placeholder-class="h8">
                </view>
            </view>
            <!-- #endif -->
            <view class="pb-safe-area">
                <view class="py-10">
                    <view class="flex flex-center">
                        <view class="bg-primary text-white rounded-round w-50 py-4 font-weight-600 text-center"
                            hover-class="bg-primary-dark-1" @tap="submit">登录/注册</view>
                    </view>
                    <view class="flex flex-center mt-4" v-if="$utils.$system.isWechat() && WEBCONFIG.wx_state">
                        <view class="h10 text-primary py-4" @tap.stop="nav = 'wechat'">微信公众号一键登录</view>
                    </view>
                    <view class="flex flex-center mt-6" @tap="form.agreement = !form.agreement">
                        <uni-icons type="circle-filled" v-if="form.agreement" color="var(--theme-color)" />
                        <uni-icons type="circle" v-else color="var(--theme-color)" />
                        <view class="h10 text-dark-light-5 pl-2">请阅读并同意</view>
                        <view class="h10 text-primary ml-2" @tap.stop="openAgreement">《用户协议》</view>
                    </view>
                </view>
            </view>
        </template>
    </view>
</template>

<script>
import { mapState } from 'vuex'
export default {
    props:{
        showLogo:{
            type:Boolean,
            default:true
        }
    },
    computed: mapState({
        WEBCONFIG: state => state.WEBCONFIG
    }),
    data() {
        return {
            showAgreementModalState: false,
            nav: 'wechat',
            mobile: '',
            captchaUrl: '',
            form: {
                mobile: '',
                imgcode: '',
                vcode: '',
                code: '',
                avatar: '',
                nickname: '',
                agreement: false
            },
            vcodeBtn: {
                text: '获取验证码',
                disabled: false
            }
        }
    },
    created() {
        this.captchaUrl = this.$utils.$http.baseURL + 'Login/captcha';
        // #ifdef MP-WEIXIN
        showAgreementModal();
        // #endif
    },
    methods: {
        show() {
            // #ifdef H5
            this.form.agreement = true;
            // #endif

            // #ifdef MP-WEIXIN
            uni.showLoading({
                title: '登录中...',
                mask: true
            })
            wx.login({
                success: (res) => {
                    if (res.code) {
                        this.form.code = res.code;
                        this.$utils.$api.Login.wechatMPCode(res.code).then((res) => {
                            this.$utils.$message.success('登录成功');
                            this.$store.dispatch('setUserInfo', res.data).then(() => {
                                this.restForm();
                                this.$emit('success');
                            })
                        }).catch((err) => {
                            if (err.code === this.$utils.$http.ResponseCode.NEED_LOGIN) {
                                uni.showModal({
                                    title: '提示',
                                    content: '登录失败，' + err.msg,
                                    showCancel: false,
                                    success: () => {
                                        this.$emit('fail');
                                    }
                                })
                            } else {
                                this.$emit('fail');
                            }
                        }).finally(() => {
                            uni.hideLoading();
                        })
                    } else {
                        uni.hideLoading();
                        uni.showModal({
                            title: '提示',
                            content: '登录失败，' + res.errMsg,
                            showCancel: false,
                            success: () => {
                                this.$emit('fail');
                            }
                        })
                    }
                },
                fail: (err) => {
                    uni.hideLoading();
                    uni.showModal({
                        title: '提示',
                        content: '微信登录失败，' + err.errMsg,
                        showCancel: false,
                        success: () => {
                            this.$emit('fail');
                        }
                    })
                }
            })
            // #endif
        },
        formatMobile() {
            let phoneNumber = this.mobile.replace(/\D/g, '');
            this.form.mobile = phoneNumber;
            // 格式化手机号：188 8888 8888
            if (phoneNumber.length > 3 && phoneNumber.length < 8) {
                phoneNumber = phoneNumber.replace(/(\d{3})(\d{1,4})/, '$1 $2');
            } else if (phoneNumber.length >= 8) {
                phoneNumber = phoneNumber.replace(/(\d{3})(\d{1,4})(\d{1,4})/, '$1 $2 $3');
            }
            this.mobile = phoneNumber;
        },
        restForm() {
            this.mobile = '';
            this.form.mobile = '';
            this.form.vcode = '';
        },
        submit() {
            uni.showLoading({
                title: '登录中...',
                mask: true
            })
            // #ifdef H5
            this.$utils.$api.Login.vcode(this.form).then((res) => {
                this.$utils.$message.success('登录成功');
                this.$store.dispatch('setUserInfo', res.data).then(() => {
                    this.restForm();
                    this.$emit('success');
                })
            }).catch(err => {
                this.$utils.$message.error(err.msg);
            }).finally(() => {
                uni.hideLoading();
            })
            // #endif
            // #ifdef MP-WEIXIN
            if (!this.form.agreement) {
                this.$utils.$message.error('请先阅读并同意用户协议');
                return;
            }
            this.$utils.$api.Login.wechatMP(this.form).then((res) => {
                this.$utils.$message.success('登录成功');
                this.$store.dispatch('setUserInfo', res.data).then(() => {
                    this.restForm();
                    this.$emit('success');
                })
            }).catch(err => {
                this.$utils.$message.error(err.msg);
            }).finally(() => {
                uni.hideLoading();
            })
            // #endif
        },
        getVcode() {
            if (this.vcodeBtn.disabled) { return; }
            this.$utils.$api.Login.getVcode({
                mobile: this.form.mobile,
                imgcode: this.form.imgcode
            }).then((res) => {
                this.vcodeBtn.disabled = true;
                let time = 60;
                const timer = setInterval(() => {
                    this.vcodeBtn.text = `${time}s`;
                    time--;
                    if (time < 0) {
                        clearInterval(timer);
                        this.vcodeBtn.text = '获取验证码';
                        this.vcodeBtn.disabled = false;
                    }
                }, 1000)
            }).catch(err => {
                this.$utils.$message.error(err.msg);
            });
        },
        getCaptchaUrl() {
            this.captchaUrl = this.$utils.$http.baseURL + 'Login/captcha?' + Math.random();
        },
        chooseavatar(e) {
            uni.showLoading({
                title: '上传中...',
                mask: true
            })
            this.$utils.$api.Upload.upload({
                filePath: e.detail.avatarUrl,
                name: 'file'
            }).then((res) => {
                this.form.avatar = res.data.url;
            }).catch(err => {
                this.$utils.$message.error(err.msg);
            }).finally(() => {
                uni.hideLoading();
            })
        },
        showAgreementModal() {
            if (!this.showModalAgreementModalState) {
                return;
            }
            this.showModalAgreementModalState = false;
            uni.showModal({
                title: '提示',
                content: '您是否同意用户协议？',
                cancelText: '不同意',
                confirmText: '同意',
                success: (res) => {
                    if (res.confirm) {
                        this.form.agreement = true;
                    } else if (res.cancel) {
                        this.form.agreement = false;
                    }
                }
            })
        },
        openAgreement() {
            // #ifdef MP-WEIXIN
            this.showModalAgreementModalState = true;
            // #endif
            this.$utils.$page.open('/pages/article/content?alias=user_agreement');
        },
        wxLogin() {
            this.$emit('wx-login')
        }
    }
}
</script>

<style lang="scss" scoped>
.w-30px {
    width: 30px;
}

.w-100px {
    width: 100px;
}

.captcha-image {
    height: 60px;
    width: 100px;
}

.avatar-btn {
    width: 100px;
    height: 100px;
    border-radius: 50%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;

    .avatar {
        width: 100px;
        height: 100px;
        border-radius: 50%;
    }
}

.flex {
    display: flex;
}

.flex-center,
.flex-x-center {
    justify-content: center;
}

.flex-center,
.flex-y-center {
    align-items: center;
}

.flex-1 {
    flex: 1;
}

.pt-2 {
    padding-top: 10rpx;
}

.px-4,
.p-4 {
    padding-left: 20rpx;
    padding-right: 20rpx;
}

.py-4,
.p-4 {
    padding-top: 20rpx;
    padding-bottom: 20rpx;
}

.h8 {
    font-size: 28rpx;
}

.font-weight-600 {
    font-weight: 600;
}

.px-10,
.p-10 {
    padding-left: 60rpx;
    padding-right: 60rpx;
}

.py-10,
.p-10 {
    padding-top: 60rpx;
    padding-bottom: 60rpx;
}

.mt-4 {
    margin-top: 20rpx;
}

.mx-4,
.m-4 {
    margin-left: 20rpx;
    margin-right: 20rpx;
}

.mt-6,
.m-6 {
    margin-top: 30rpx;
}

.text-center {
    text-align: center;
}

.overflow-hidden {
    overflow: hidden;
}

.overflow-auto {
    overflow: auto;
}

.flex-column {
    flex-direction: column;
}

.bg-grey {
    background-color: var(--theme-bg-color-light);
}

.rounded-round {
    border-radius: 20rpx;
}

.h4 {
    font-size: 32px;
    box-sizing: content-box;
}

.text-primary {
    color: var(--theme-color)
}

.bg-primary {
    background-color: var(--theme-btn-color);
}

.w-50 {
    width: 50%;
}

.h10 {
    font-size: 24rpx;
}

.text-dark-light-5 {
    color: $u-light-color;
}
.logo {
		height: 200rpx;
		width: 200rpx;
		margin-bottom: 30rpx;
		border-radius: 30rpx;
	}
</style>